/*
 * @Author: 聆风
 * @Date: 2025-08-23 17:50:23
 * @LastEditors: 聆风 522361856@qq.com
 * @LastEditTime: 2025-08-24 01:18:26
 * @FilePath: \​monoFE​​\scripts\utils.js
 *
 * Copyright (c) 2025 by 聆风, All Rights Reserved.
 */
import fs from "fs"; // 改为导入整个fs模块
import path from "path"; // 添加path模块导入
import { fileURLToPath } from "url";

// 获取 packages 目录路径
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
export const packagesDir = path.resolve(__dirname, "../packages");
export const rootDir = path.resolve(__dirname, "..");

// 获取所有包
export function getPackages() {
  return fs.readdirSync(packagesDir).filter((dir) => {
    const dirPath = path.join(packagesDir, dir);
    return fs.statSync(dirPath).isDirectory();
  });
}

// 读取包的 package.json
export function readPackageJson(pkg) {
  const packageJsonPath = path.join(packagesDir, pkg, "package.json");
  return JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
}

// 读取当前的 tsconfig.json
export function readTsconfigJson() {
  const tsconfigPath = path.join(rootDir, "tsconfig.json");
  let file = JSON.parse(fs.readFileSync(tsconfigPath, "utf8"));
  return file;
}

// 同步递归删除函数
function deleteRecursiveSync(targetPath) {
  try {
    const stats = fs.statSync(targetPath);
    if (!stats.isDirectory()) {
      fs.unlinkSync(targetPath); // 同步删除文件
      return;
    }

    // 读取目录内容
    const files = fs.readdirSync(targetPath);
    files.forEach((file) => {
      const curPath = path.join(targetPath, file);
      deleteRecursiveSync(curPath); // 递归删除子项
    });

    // 删除空目录
    fs.rmdirSync(targetPath);
  } catch (err) {
    if (err.code !== "ENOENT") throw err; // 忽略"目录不存在"错误
  }
}

export function cleanDist(pkg) {
  const distPath = path.join(packagesDir, pkg, "dist");
  console.log(`🧹 清理目录: ${distPath}`);

  // 检查目录是否存在
  if (fs.existsSync(distPath)) {
    deleteRecursiveSync(distPath);
  } else {
    console.log(`ℹ️ 目录不存在: ${distPath}`);
  }
}
